/*
 * @Author: biankai
 * @Date: 2021-11-04 14:27:50
 * @LastEditTime: 2021-11-05 15:55:26
 * @LastEditors: biankai
 * @FilePath: /gitee/devops_service/src/services/kubernetes/service.service.ts
 */
import {
    Injectable,
    Inject,
    HttpService,
    BadRequestException,
} from '@nestjs/common';
import * as kubernetes from '@kubernetes/client-node';
import { BaseService } from './base.service';
@Injectable()
export class ServiceService extends BaseService {
    private readonly k8sApi: kubernetes.CoreV1Api;

    constructor(@Inject(HttpService) private readonly httpService: HttpService) {
        super()
        const kc = new kubernetes.KubeConfig();
        kc.loadFromFile(this.k8sConfig)
        this.k8sApi = kc.makeApiClient(kubernetes.CoreV1Api);
    }
    async listNamespacedService(namespaceName) {
        const resBody = await this.k8sApi.listNamespacedService(namespaceName);
        return await resBody.body;
    }
    async readNamespacedService(namespaceName, name) {
        const resBody = await this.k8sApi.readNamespacedService(name, namespaceName);
        return await resBody.body;
    }
    async createNamespacedService(namespaceName, service) {
        var options = {
            "apiVersion": "v1",
            "kind": "Service",
            "metadata": {
                "labels": {
                    "app": service.name
                },
                "name": service.name
            },
            "spec": {
                "ports": [{
                    "port": 80,
                    "targetPort": 80 as Object
                }],
                "selector": {
                    "app": service.name
                },
                "type": "NodePort"
            }
        }

        const resBody = await this.k8sApi.createNamespacedService(namespaceName, options);
        return await resBody.body;
    }
    async replaceNamespacedService(namespaceName, name, service) {
        var options = {
            "apiVersion": "v1",
            "kind": "Service",
            "metadata": {
                "labels": {
                    "app": service.name
                },
                "name": service.name
            },
            "spec": {
                "ports": [{
                    "port": 80,
                    "targetPort": 80 as Object
                }],
                "selector": {
                    "app": service.name
                },
                "type": "NodePort"
            }
        }
        const resBody = await this.k8sApi.replaceNamespacedService(name, namespaceName, options);
        return await resBody.body;
    }
    async deleteNamespacedService(namespaceName, name) {
        const resBody = await this.k8sApi.deleteNamespacedService(name, namespaceName);
        return await resBody.body;
    }
}
